<template>
  <div class="project-detail">
    <div class="page-header">
      <div class="back-button">
        <el-button type="text" size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回项目列表
        </el-button>
      </div>
      <h2 class="page-title">项目详情</h2>
    </div>
    
    <el-row :gutter="20">
      <!-- 项目基本信息卡片 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <el-card class="detail-card info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h2 class="project-title">{{ project.name }}</h2>
              <el-tag :type="getStatusType(project.status)" size="large" effect="plain">
                {{ project.statusText }}
              </el-tag>
            </div>
          </template>
          
          <div class="description-section">
            <h3>项目描述</h3>
            <p class="description">{{ project.description }}</p>
          </div>

          <div class="progress-section">
            <div class="progress-header">
              <h3>项目进度</h3>
              <span class="progress-percentage">{{ project.progress }}%</span>
            </div>
            <el-progress 
              :percentage="project.progress" 
              :status="getProgressStatus(project.progress)"
              :format="formatProgress"
              :stroke-width="16"
            ></el-progress>
          </div>

          <div class="meta-grid">
            <div class="meta-item">
              <h4>项目经理</h4>
              <div class="meta-content">
                <el-avatar :size="32" :src="findManagerAvatar()"></el-avatar>
                <span>{{ project.manager }}</span>
              </div>
            </div>

            <div class="meta-item">
              <h4>开始日期</h4>
              <div class="meta-content">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(project.startDate) }}</span>
              </div>
            </div>

            <div class="meta-item">
              <h4>截止日期</h4>
              <div class="meta-content">
                <el-icon><AlarmClock /></el-icon>
                <span>{{ formatDate(project.deadline) }}</span>
              </div>
            </div>

            <div class="meta-item">
              <h4>预计剩余天数</h4>
              <div class="meta-content">
                <el-icon><Timer /></el-icon>
                <span>{{ getRemainingDays() }} 天</span>
              </div>
            </div>
          </div>

          <div class="action-bar">
            <el-button type="primary" @click="editProject">编辑项目</el-button>
            <el-button :type="getChangeStatusType()" @click="openStatusDialog">{{ getChangeStatusText() }}</el-button>
            <el-button type="danger" @click="openDeleteConfirm">删除项目</el-button>
          </div>
        </el-card>

        <!-- 项目文档卡片 -->
        <el-card class="detail-card document-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>项目文档</h3>
              <el-button type="primary" plain size="small">上传文档</el-button>
            </div>
          </template>
          
          <el-empty v-if="documents.length === 0" description="暂无项目文档"></el-empty>
          
          <div v-else class="document-list">
            <div v-for="doc in documents" :key="doc.id" class="document-item">
              <div class="document-icon">
                <el-icon v-if="doc.type === 'pdf'"><Document /></el-icon>
                <el-icon v-else-if="doc.type === 'excel'"><Grid /></el-icon>
                <el-icon v-else-if="doc.type === 'word'"><Tickets /></el-icon>
                <el-icon v-else><Files /></el-icon>
              </div>
              <div class="document-info">
                <div class="document-name">{{ doc.name }}</div>
                <div class="document-meta">
                  <span>{{ doc.size }}MB</span>
                  <span>{{ doc.uploadDate }}</span>
                </div>
              </div>
              <div class="document-actions">
                <el-button type="primary" size="small" text><el-icon><Download /></el-icon></el-button>
                <el-button type="danger" size="small" text><el-icon><Delete /></el-icon></el-button>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 任务卡片 -->
        <el-card class="detail-card task-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>项目任务</h3>
              <el-button type="success" plain size="small">添加任务</el-button>
            </div>
          </template>
          
          <el-empty v-if="tasks.length === 0" description="暂无项目任务"></el-empty>
          
          <div v-else class="task-list">
            <el-table :data="tasks" style="width: 100%">
              <el-table-column label="任务名称" prop="name"></el-table-column>
              <el-table-column label="负责人" width="120">
                <template #default="scope">
                  <div class="assignee">
                    <el-avatar :size="24" :src="scope.row.assigneeAvatar"></el-avatar>
                    <span>{{ scope.row.assignee }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="截止日期" width="120" prop="deadline"></el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getTaskStatusType(scope.row.status)" size="small">
                    {{ scope.row.statusText }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default>
                  <el-button type="primary" size="small" text>编辑</el-button>
                  <el-button type="danger" size="small" text>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧信息栏 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <!-- 团队成员卡片 -->
        <el-card class="detail-card team-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>项目团队</h3>
              <el-button type="success" plain size="small">添加成员</el-button>
            </div>
          </template>
          
          <div class="team-list">
            <div v-for="member in project.teamMembers" :key="member.id" class="team-member">
              <el-avatar :size="40" :src="member.avatar"></el-avatar>
              <div class="member-info">
                <div class="member-name">{{ member.name }}</div>
                <div class="member-role" v-if="member.name === project.manager">项目经理</div>
                <div class="member-role" v-else>团队成员</div>
              </div>
              <el-button 
                v-if="member.name !== project.manager"
                size="small" 
                type="danger" 
                text
                @click="removeMember(member.id)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
        
        <!-- 项目活动记录卡片 -->
        <el-card class="detail-card activity-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>最近活动</h3>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 状态变更对话框 -->
    <el-dialog
      v-model="showStatusDialog"
      title="更改项目状态"
      width="400px"
    >
      <el-form label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(project.status)">{{ project.statusText }}</el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="newStatus" style="width: 100%">
            <el-option label="进行中" value="active"></el-option>
            <el-option label="已暂停" value="paused"></el-option>
            <el-option label="已完成" value="completed"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showStatusDialog = false">取消</el-button>
          <el-button type="primary" :loading="changingStatus" @click="changeProjectStatus">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="showDeleteConfirm"
      title="删除项目"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>您确定要删除项目 <strong>{{ project.name }}</strong> 吗？</p>
        <p class="warning-text">此操作将永久删除该项目，且无法恢复！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteConfirm = false">取消</el-button>
          <el-button type="danger" :loading="deleting" @click="deleteProject">
            确认删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  Document, Grid, Tickets, Files, Download, Delete, Calendar,
  AlarmClock, Timer, WarningFilled, Back
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const route = useRoute();

// 返回项目列表
const goBack = () => {
  router.push('/projects');
};

// 页面状态
const loading = ref(true);
const showStatusDialog = ref(false);
const showDeleteConfirm = ref(false);
const changingStatus = ref(false);
const deleting = ref(false);
const newStatus = ref('');

// 项目数据
const project = ref({
  id: 1,
  name: '企业官网重构',
  description: '对公司官网进行全面改版，提升用户体验和转化率。项目包括首页、产品页、关于我们、新闻中心等页面的设计和开发。主要目标是提高网站加载速度、优化移动端体验以及增加转化率。团队将采用最新的前端技术栈，包括Vue 3、TailwindCSS等框架，并结合良好的UI/UX设计原则进行实施。',
  manager: '张三',
  startDate: '2023-01-15',
  deadline: '2023-05-30',
  status: 'active',
  statusText: '进行中',
  progress: 65,
  teamMembers: [
    { id: 1, name: '张三', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
    { id: 2, name: '李四', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
    { id: 3, name: '王五', avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' },
    { id: 4, name: '赵六', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' }
  ]
});

// 任务数据
const tasks = ref([
  {
    id: 1,
    name: '页面设计',
    assignee: '李四',
    assigneeAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    deadline: '2023-02-28',
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 2,
    name: '前端开发',
    assignee: '王五',
    assigneeAvatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    deadline: '2023-04-15',
    status: 'inProgress',
    statusText: '进行中'
  },
  {
    id: 3,
    name: '后端API开发',
    assignee: '赵六',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    deadline: '2023-04-30',
    status: 'inProgress',
    statusText: '进行中'
  },
  {
    id: 4,
    name: '测试和上线',
    assignee: '张三',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    deadline: '2023-05-25',
    status: 'pending',
    statusText: '待处理'
  }
]);

// 文档数据
const documents = ref([
  {
    id: 1,
    name: '项目需求文档.pdf',
    type: 'pdf',
    size: '1.5',
    uploadDate: '2023-01-18'
  },
  {
    id: 2,
    name: '设计稿.pdf',
    type: 'pdf',
    size: '3.2',
    uploadDate: '2023-02-05'
  },
  {
    id: 3,
    name: '项目进度表.xlsx',
    type: 'excel',
    size: '0.8',
    uploadDate: '2023-03-10'
  },
  {
    id: 4,
    name: '会议纪要.docx',
    type: 'word',
    size: '0.5',
    uploadDate: '2023-03-25'
  }
]);

// 活动记录
const activities = ref([
  {
    content: '张三创建了项目',
    time: '2023-01-15 09:30',
    type: 'primary'
  },
  {
    content: '李四上传了"项目需求文档.pdf"',
    time: '2023-01-18 14:20',
    type: ''
  },
  {
    content: '王五完成了任务"页面设计"',
    time: '2023-02-28 16:45',
    type: 'success'
  },
  {
    content: '张三更新了项目进度为65%',
    time: '2023-03-25 10:15',
    type: 'warning'
  }
]);

// 根据ID获取项目数据
const fetchProjectData = async (id) => {
  loading.value = true;
  try {
    // 在真实环境中，这里应该是一个API调用
    // 目前使用模拟数据
    console.log(`获取项目ID ${id} 的数据`);
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    loading.value = false;
  } catch (error) {
    console.error('获取项目数据失败:', error);
    ElMessage.error('获取项目数据失败');
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'active': return 'primary';
    case 'completed': return 'success';
    case 'paused': return 'warning';
    default: return 'info';
  }
};

// 获取进度条状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success';
  if (progress > 70) return '';
  if (progress > 30) return 'warning';
  return 'exception';
};

// 获取任务状态类型
const getTaskStatusType = (status) => {
  switch (status) {
    case 'completed': return 'success';
    case 'inProgress': return 'primary';
    case 'pending': return 'info';
    case 'overdue': return 'danger';
    default: return 'info';
  }
};

// 获取状态变更按钮类型
const getChangeStatusType = () => {
  switch (project.value.status) {
    case 'active': return 'warning';
    case 'paused': return 'primary';
    case 'completed': return 'info';
    default: return 'info';
  }
};

// 获取状态变更按钮文本
const getChangeStatusText = () => {
  switch (project.value.status) {
    case 'active': return '暂停项目';
    case 'paused': return '继续项目';
    case 'completed': return '重新开始';
    default: return '更改状态';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化进度提示
const formatProgress = (val) => {
  return `${val}%`;
};

// 计算剩余天数
const getRemainingDays = () => {
  if (project.value.status === 'completed') return 0;
  
  const today = new Date();
  const deadline = new Date(project.value.deadline);
  const diffTime = deadline - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  return diffDays > 0 ? diffDays : 0;
};

// 查找项目经理头像
const findManagerAvatar = () => {
  const manager = project.value.teamMembers.find(m => m.name === project.value.manager);
  return manager ? manager.avatar : '';
};

// 打开状态变更对话框
const openStatusDialog = () => {
  newStatus.value = project.value.status;
  showStatusDialog.value = true;
};

// 变更项目状态
const changeProjectStatus = async () => {
  if (newStatus.value === project.value.status) {
    showStatusDialog.value = false;
    return;
  }
  
  changingStatus.value = true;
  
  try {
    // 在真实环境中，这里应该是一个API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 更新项目状态
    project.value.status = newStatus.value;
    switch (newStatus.value) {
      case 'active':
        project.value.statusText = '进行中';
        break;
      case 'paused':
        project.value.statusText = '已暂停';
        break;
      case 'completed':
        project.value.statusText = '已完成';
        project.value.progress = 100;
        break;
    }
    
    // 添加一条活动记录
    activities.value.unshift({
      content: `张三将项目状态更改为"${project.value.statusText}"`,
      time: new Date().toLocaleString(),
      type: getStatusType(newStatus.value)
    });
    
    ElMessage.success('项目状态已更新');
    showStatusDialog.value = false;
  } catch (error) {
    console.error('更新项目状态失败:', error);
    ElMessage.error('更新项目状态失败');
  } finally {
    changingStatus.value = false;
  }
};

// 打开删除确认对话框
const openDeleteConfirm = () => {
  showDeleteConfirm.value = true;
};

// 删除项目
const deleteProject = async () => {
  deleting.value = true;
  
  try {
    // 在真实环境中，这里应该是一个API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    ElMessage.success('项目已删除');
    showDeleteConfirm.value = false;
    
    // 跳转回项目列表页
    router.push('/projects');
  } catch (error) {
    console.error('删除项目失败:', error);
    ElMessage.error('删除项目失败');
  } finally {
    deleting.value = false;
  }
};

// 编辑项目
const editProject = () => {
  ElMessage.info('编辑项目功能尚未实现');
  // 实际实现中可以跳转到编辑页面或打开编辑对话框
};

// 移除团队成员
const removeMember = (memberId) => {
  ElMessageBox.confirm('确定要从项目中移除该成员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = project.value.teamMembers.findIndex(m => m.id === memberId);
    if (index !== -1) {
      const memberName = project.value.teamMembers[index].name;
      project.value.teamMembers.splice(index, 1);
      
      // 添加一条活动记录
      activities.value.unshift({
        content: `张三将成员 ${memberName} 从项目中移除`,
        time: new Date().toLocaleString(),
        type: 'danger'
      });
      
      ElMessage.success('已移除团队成员');
    }
  }).catch(() => {});
};

// 页面加载时获取项目数据
onMounted(() => {
  const projectId = route.params.id || 1;
  fetchProjectData(projectId);
});
</script>

<style lang="scss" scoped>
.project-detail {
  padding: 20px;
  
  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    
    .back-button {
      margin-right: 12px;
    }
    
    .page-title {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .detail-card {
    margin-bottom: 20px;
    border-radius: 8px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h2, h3 {
        margin: 0;
        font-weight: 600;
      }
    }
  }
  
  .info-card {
    .project-title {
      font-size: 20px;
      color: #303133;
    }
    
    .description-section {
      margin-bottom: 20px;
      
      h3 {
        font-size: 16px;
        margin-bottom: 10px;
        color: #606266;
      }
      
      .description {
        color: #606266;
        line-height: 1.6;
        margin: 0;
      }
    }
    
    .progress-section {
      margin: 20px 0;
      
      .progress-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        h3 {
          font-size: 16px;
          color: #606266;
          margin: 0;
        }
        
        .progress-percentage {
          font-weight: bold;
          color: #409EFF;
        }
      }
    }
    
    .meta-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      margin: 20px 0;
      
      .meta-item {
        h4 {
          font-size: 14px;
          color: #909399;
          margin: 0 0 8px 0;
          font-weight: normal;
        }
        
        .meta-content {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #303133;
          font-weight: 500;
          
          .el-icon {
            color: #909399;
          }
        }
      }
    }
    
    .action-bar {
      display: flex;
      gap: 10px;
      margin-top: 30px;
    }
  }
  
  .document-card, .task-card {
    .document-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .document-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border-radius: 6px;
        background-color: #f5f7fa;
        
        &:hover {
          background-color: #ecf5ff;
        }
        
        .document-icon {
          font-size: 24px;
          color: #909399;
          margin-right: 12px;
        }
        
        .document-info {
          flex: 1;
          
          .document-name {
            font-weight: 500;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .document-meta {
            font-size: 12px;
            color: #909399;
            display: flex;
            gap: 10px;
          }
        }
        
        .document-actions {
          display: flex;
          gap: 5px;
        }
      }
    }
  }
  
  .team-card {
    .team-list {
      display: flex;
      flex-direction: column;
      gap: 15px;
      
      .team-member {
        display: flex;
        align-items: center;
        padding: 10px;
        border-radius: 6px;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        .member-info {
          flex: 1;
          margin-left: 12px;
          
          .member-name {
            font-weight: 500;
            color: #303133;
          }
          
          .member-role {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .activity-card {
    .el-timeline {
      padding-left: 5px;
      
      .el-timeline-item {
        padding-bottom: 20px;
        
        &:last-child {
          padding-bottom: 0;
        }
      }
    }
  }
  
  .task-list {
    .assignee {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .delete-confirm {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      font-size: 48px;
      color: #E6A23C;
      margin-bottom: 16px;
    }
    
    p {
      margin: 8px 0;
      font-size: 16px;
    }
    
    .warning-text {
      color: #F56C6C;
      font-weight: bold;
    }
  }
}
</style> 